<template>
    <el-dialog v-model="visible" title="发布帖子" width="45%" align-center :show-close="false" :close-on-click-modal="false">
        <el-form :rules="rules" :model="form" ref="formRef" v-loading="loading">
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入帖子的标题" />
            </el-form-item>
            <el-form-item label="描述" prop="detail">
                <el-input v-model="form.detail" :rows="3" type="textarea" placeholder="来吧，尽情发挥吧..." />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="submit" :icon="Promotion" :loading="loading">发布</el-button>
                <el-button @click="visible = false">返回</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { Promotion } from '@element-plus/icons-vue'
import type { FormRules } from 'element-plus'
import { reactive, ref } from 'vue';
import { addInvitation } from '@/api/invitation'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refresh'])
const visible = ref(false);
const emitShow = () => {
    visible.value = true;
    formRef.value.resetFields()
        ;
}
// 传递给父组件的方法
defineExpose({ emitShow })

const form = reactive({
    title: '',
    detail: ''
})

const loading = ref(false)
const formRef = ref(null as any)

const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 5, max: 31, message: '帖子标题为5-31字', trigger: 'blur' },
    ],
    detail: [
        { required: true, message: '请输入帖子描述', trigger: 'blur' },
        { min: 10, max: 255, message: '描述至少10字，至多255字', trigger: 'blur' },
    ],
})

const submit = () => {
    formRef.value.validate((valid: boolean) => {
        if (!valid) return;
        loading.value = true;
        addInvitation({ ...form }).then((res: any) => {
            if (res.code !== 200) return ElMessage.error(res.message || '添加失败')
            ElMessage.success(res.msg)
            visible.value = false;
            emit('refresh')

        }).finally(() => {
            loading.value = false;
        })
    })
}
</script>

<style scoped lang="scss"></style>